﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.Admin.Application.Service;
using Windows.Admin.Application.Service.Privilege.Dtos;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Admin.Infrastructure.EFCore.Extensions;
using Windows.Application.Share;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Security;
using Windows.Infrastructure.Share.Tools;
using Windows.SeedWord;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Windows.Admin.Application
{
    public class ShortcutService : IShortcutService
    {
        private readonly ICurrentUser _currentUser;
        private readonly AdminDbContext _db;
        public ShortcutService(ICurrentUser currentUser, AdminDbContext db)
        {
            _currentUser = currentUser;
            _db = db;
        }
        /// <summary>
        /// 设置快捷方式
        /// </summary>
        /// <returns></returns>
        public async Task SetShortcut(ShortcutSetRequest request)
        {
            if (request.AppIds != null)
            {
                using var tran = _db.Database.BeginTransaction();
                try
                {
                    var shortcuts = await _db.Shortcut.Where(x => x.UserId == _currentUser.Id).ToListAsync();
                    _db.RemoveRange(shortcuts);
                    List<Shortcut> lists = new();
                    foreach (var appId in request.AppIds)
                    {
                        Shortcut shortcut = new()
                        {
                            UserId = _currentUser.Id,
                            AppId = appId
                        };
                        lists.Add(shortcut);
                    }
                    await _db.AddRangeAsync(lists);
                    await _db.SaveChangesAsync();
                    await tran.CommitAsync();
                }
                catch (Exception)
                {
                    await tran.RollbackAsync();
                    throw;
                }
            }
        }
    }
}
